#!/bin/bash
### BEGIN INIT INFO
# Provides: shutdownbefore
# Required-Start:
# Required-Stop:
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:
# Description:
### END INIT INFO

MODULES="sec-dashboard-webui sec-dashboard-service kun-system kun-auth kun-device kun-service-cipher kun-service-kms kun-gateway"

stopService() {
  echo "Try stop $1..."    
  if [ ! -z `docker ps -q --filter name=$1` ]; then
    docker stop $1
  fi
}

stopMySQL() {
  echo "Try stop sec-mysql..."    
  if [ ! -z `docker ps -q --filter name=sec-mysql` ]; then
    docker exec -i sec-mysql /usr/bin/mysqladmin -uroot -p123456 shutdown
  fi
}

stopContainers() {
  echo "stop containers script"
  
  for module in $MODULES; do
    stopService $module
  done

  stopService sec-nacos
  stopService sec-redis
  stopMySQL
}

startService() {
  echo "Try start $1..."    
  if [ ! -z `docker ps -q -a --filter name=$1` ]; then
    docker restart $1
  fi
}

startMySQL() {
  echo "Try start sec-mysql..."    
  if [ ! -z `docker ps -q --filter name=sec-mysql` ]; then
    docker exec -i sec-mysql /usr/bin/mysqladmin -uroot -p123456 shutdown
    sleep 10
  fi
  if [ ! -z `docker ps -q -a --filter name=sec-mysql` ]; then
    docker start sec-mysql
    sleep 10
  fi
}

startContainers() {
  echo "start containers script"  

  startMySQL
  startService sec-redis
  startService sec-nacos
  
  for module in $MODULES; do
    startService $module
  done
}

case "${1:-''}" in
  'start')
        startContainers
        ;;
  'stop')
	stopContainers
        ;;
  *)
        ;;
esac
